package com.gin.no_gay_alliance.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.NonNull;

import com.gin.no_gay_alliance.manager.provider.ResourceManager;
import com.gin.no_gay_alliance.utils.MyHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 颜色选择器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/28 16:47
 **/
public class ColorSelectorWebView extends WebView {
    public static final String PLACEHOLDER_CONTENT = "[正文占位]";
    public static final String TEMPLATE_SPAN = "<span class='color-span' style='background-color: %s;' onclick='android.chooseColor(\"%s\")'>&nbsp;</span>";

    final MyHandler handler;

    public ColorSelectorWebView(@NonNull Context context, MyHandler handler) {
        super(context);
        this.handler = handler;
        init();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init() {
        WebSettings settings = getSettings();
        //设置WebView属性,运行执行js脚本
        settings.setJavaScriptEnabled(true);
        // 请求颜色数据
        ResourceManager.bbsCodeCoreProvider().async(false, body -> {
            // 颜色名称
            List<String> fontColor = body.getFontColor();
            // 转换为span
            String spans = fontColor.stream().map(c -> String.format(TEMPLATE_SPAN, c, c)).collect(Collectors.joining());

            String html = getTemplate().replace(PLACEHOLDER_CONTENT, spans);
            // 渲染
            handler.post(() -> loadDataWithBaseURL(null, html, "text/html", "UTF-8", null));
        });
    }

    /**
     * 从assets文件夹中加载模板
     *
     * @return 模板
     */
    private String getTemplate() {
        try {
            AssetManager assetManager = getContext().getAssets();
            InputStream is = assetManager.open("colorSelector.html");
            InputStreamReader isReader = new InputStreamReader(is);
            BufferedReader bfReader = new BufferedReader(isReader);
            return bfReader.lines().collect(Collectors.joining());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
